package com.example.coursehub.service.impl;

import com.example.coursehub.entity.Material;
import com.example.coursehub.entity.StudentMaterial;
import com.example.coursehub.entity.StudentMaterialId;
import com.example.coursehub.entity.User;
import com.example.coursehub.repository.MaterialRepository;
import com.example.coursehub.repository.StudentMaterialRepository;
import com.example.coursehub.repository.UserRepository;
import com.example.coursehub.service.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class MaterialSeviceImpl implements MaterialService {

//    @Autowired
    private MaterialRepository materialRepository;
//    @Autowired
    private UserRepository userRepository;

    private final StudentMaterialRepository studentMaterialRepository;

    private final List<Material> materialList = new ArrayList<>(); // 模拟数据库

    public MaterialSeviceImpl(
            MaterialRepository materialRepository,
            UserRepository userRepository,
            StudentMaterialRepository studentMaterialRepository
    ) {
        this.materialRepository = materialRepository;
        this.userRepository = userRepository;
        this.studentMaterialRepository = studentMaterialRepository;
    }

    @Override
    public Material uploadMaterial(Material material) {
        return materialRepository.save(material);
    }
    public List<Material> getMaterialByChapter(String chapterId){
        return materialRepository.findByChapter_ChapterId(chapterId);
    }
    public List<Material> getMaterialByCourseId(String courseId){
        return materialRepository.findByCourse_CourseId(courseId);
    }
    @Override
    public void deleteMaterial(String materialId) {
        materialRepository.deleteById(materialId);
    }

    @Override
    public Optional<Material> getMaterialById(String materialId) {
        return materialRepository.findById(materialId);
    }

    @Override
    public List<Material> getMaterialsByCourseAndChapter(String courseId, String chapterId) {
        return materialRepository.findByCourse_CourseIdAndChapter_ChapterId(courseId, chapterId);
    }

    @Override
    public List<Material> findCompletedMaterialsByStudent(String userId, String chapterId) {
        // 查询学生已完成的资料关联（通过多对多表 StudentMaterial）
        return studentMaterialRepository
                .findByUser_UserIdAndMaterial_Chapter_ChapterIdAndIsFinished(userId, chapterId, true)
                .stream()
                .map(StudentMaterial::getMaterial) // 直接获取关联的 Material 实体
                .collect(Collectors.toList());
    }

    @Override
    public void updateStudentMaterialStatus(String userId, String materialId, boolean isFinished) {
        // 查找 Material 和 User
        Material material = materialRepository.findById(materialId)
                .orElseThrow(() -> new RuntimeException("Material not found: " + materialId));
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found: " + userId));

        // 创建复合主键
        StudentMaterialId id = new StudentMaterialId();
        id.setUserId(userId);
        id.setMaterialId(materialId);

        // 查找或创建记录
        StudentMaterial studentMaterial = studentMaterialRepository.findById(id)
                .orElseGet(() -> {
                    StudentMaterial newRecord = new StudentMaterial();
                    newRecord.setId(id);
                    newRecord.setMaterial(material); // 必须
                    newRecord.setUser(user);         // 必须
                    return newRecord;
                });

        // 这两行必须加，即使是老记录也要补
        studentMaterial.setMaterial(material);
        studentMaterial.setUser(user);

        // 更新完成状态
        studentMaterial.setIsFinished(isFinished);
        studentMaterialRepository.save(studentMaterial);
    }

    @Override
    public boolean getStudentMaterialStatus(String userId, String materialId) {
        // 创建复合主键
        StudentMaterialId id = new StudentMaterialId();
        id.setUserId(userId);
        id.setMaterialId(materialId);

        // 查询状态，如果不存在默认返回false
        return studentMaterialRepository.findById(id)
                .map(StudentMaterial::getIsFinished)
                .orElse(false);
    }



}
